package com.dyz.leetcode;

public class Trie208 {
    class TreeNode{
        boolean isWord = false;
        TreeNode [] children;
        public TreeNode(){
            children = new TreeNode[26];
        }
    }
    //初始化根节点
    TreeNode root;
    /** Initialize your data structure here. */
    public Trie208() {
        root = new TreeNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TreeNode curr = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            int index = c - 'a';
            if(curr.children[index]==null){
                curr.children[index] = new TreeNode();
            }
            //cur往下一定一格
            curr = curr.children[index];
        }
        curr.isWord =true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TreeNode curr = root;
        for(int i=0; i<word.length(); i++){
            char c = word.charAt(i);
            int index = c - 'a';
            if(curr.children[index]==null){
                return false;
            }
            //cur往下一定一格
            curr = curr.children[index];
        }
        return curr.isWord;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TreeNode curr = root;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix.charAt(i);
            int index = c - 'a';
            if(curr.children[index]==null){
                return false;
            }
            //cur往下一定一格
            curr = curr.children[index];
        }
        return true;

    }
}
